﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

namespace ERP.Common.Util;

public class JwtUtil
{
    public static string SECRET_KEY;
    public static byte[] SECRET_KEY_BYTES;
    public static SigningCredentials SIGNING_CREDENTIALS;

    public static string CreateJwt(long userId, string name, long roleId)
    {
        var claims = new[]
        {
            new Claim("name", name),
            new Claim("id", userId.ToString()),
            new Claim("roleId", roleId.ToString())
        };

        var token = new JwtSecurityToken(
            claims: claims,
            expires: DateTime.UtcNow.AddMinutes(60),
            signingCredentials: SIGNING_CREDENTIALS
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    public static bool VerifyJwt(string jwtToken)
    {
        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(SECRET_KEY_BYTES)
            };

            tokenHandler.ValidateToken(jwtToken, tokenValidationParameters, out var validatedToken);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }

    public static Dictionary<string, object> ParseJwtMetadata(string jwtToken)
    {
        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var jwtSecurityToken = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken;

            if (jwtSecurityToken == null)
            {
                return null;
            }

            var claims = jwtSecurityToken.Claims;
            var metadata = new Dictionary<string, object>();

            foreach (var claim in claims)
            {
                metadata.Add(claim.Type, claim.Value);
            }

            return metadata;
        }
        catch (Exception)
        {
            return null;
        }
    }
}